package org.uim.cricket.analyzer.parsers.misc.impl;

import java.util.ArrayList;

import org.uim.cricket.analyzer.parsers.misc.SimpleNameParsable;
import org.uim.cricket.entities.Player;
import org.uim.cricket.util.MyStringUtils;

/**
 * Separates any number of player string representation to respective
 * <code>Player</code> objects. Each player's string must be separated
 * by a comma ('<code>,</code>') and the final two players may be
 * combined by using <code>" and "</code> substring.
 * 
 * <p>As example, suppose input String is 
 * <code>"A Isuru (Sri Lanka), B Madushanka (England) and C Weerarathna"</code>, 
 * then output player instances will be players with "A Isuru",
 * "B Madushanka" and "C Weerarathna". Their respective countries will be 
 * embedded into their Player objects, <b> if any found</b>.</p>
 * 
 * @version 1.0
 * @author iweerarathna
 */
public class MultiSimpleNameParser implements SimpleNameParsable {

	@Override
	public Player[] parserNames(String source) {
		if (source == null || source.length() == 0) return null;
		String[] names = source.split(",");
		ArrayList<Player> list = new ArrayList<Player>();
		
		for (int i=0;i<names.length;i++) {
			names[i]=names[i].trim();
			Player[] ps = this.parserSingleName(names[i]);
			if (ps==null) continue;
			
			for (int j=0;j<ps.length;j++) {
				list.add(ps[j]);
			}
		}
		
		Player[] array = new Player[list.size()];
		list.toArray(array);
		return array;
	}
	
	public Player[] parserSingleName(String source) {
        if (source == null || source.length() == 0) return null;
        int pos = source.indexOf(" and ");
        
        if (pos < 0) {
            Player p = this.getPlayer(source);
            return new Player[] {p};
        }
        
        String tmp = source.substring(0, pos).trim();
        Player[] ps = new Player[2];
        ps[0] = this.getPlayer(tmp);
        tmp = source.substring(pos + 5).trim();
        ps[1] = this.getPlayer(tmp);
        
        return ps;
    }
	
	private Player getPlayer(String source) {
        Player p = new Player();
        int ppos = source.indexOf('(');
        if (ppos > 0) {
            p.setTitleName(source.substring(0, source.indexOf('(')).trim());
            String country = MyStringUtils.inBetween(source, "(", ")");
            p.setCountry(country);
        } else {
            p.setTitleName(source);
        }
        return p;
    }

}
